package simplyrugby.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import simplyrugby.entity.Role;
import simplyrugby.entity.RoleMenu;
import simplyrugby.mapper.MenuMapper;
import simplyrugby.mapper.RoleMapper;
import simplyrugby.mapper.RoleMenuMapper;
import simplyrugby.service.RoleService;

/**
 * @author admin
 * @description 针对表【role(角色)】的数据库操作Service实现
 * @createDate 2025-03-29 18:35:16
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
        implements RoleService {

    private final MenuMapper menuMapper;
    private final RoleMenuMapper roleMenuMapper;

    @Override
    public Page<Role> list(Integer pageNum, Integer pageSize, Role role) {
        LambdaQueryWrapper<Role> wrapper = Wrappers.lambdaQuery(Role.class)
                .eq(!ObjectUtils.isEmpty(role.getId()), Role::getId, role.getId())
                .like(!ObjectUtils.isEmpty(role.getName()), Role::getName, role.getName());

        Page<Role> page = new Page<>(pageNum, pageSize);
        this.page(page, wrapper);
        return page;
    }

    @Override
    public Role details(String id) {
        Role role = baseMapper.selectById(id);
        role.setMenuList(menuMapper.selectListByRoleId(role.getId()));
        return role;
    }

    @Override
    public boolean addRole(Role role) {
        role.setId(String.valueOf(IdWorker.getId()));
        if (!role.getMenuIds().isEmpty()) {
            for (String menuId : role.getMenuIds()) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(role.getId());
                roleMenu.setMenuId(menuId);
                roleMenuMapper.insert(roleMenu);
            }
        }
        int insert = baseMapper.insert(role);
        return insert > 0;
    }

    @Override
    public boolean updateRole(Role role) {
        roleMenuMapper.delete(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, role.getId()));

        if (!role.getMenuIds().isEmpty()) {
            for (String menuId : role.getMenuIds()) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(role.getId());
                roleMenu.setMenuId(menuId);
                roleMenuMapper.insert(roleMenu);
            }
        }
        int insert = baseMapper.updateById(role);
        return insert > 0;
    }
}




